#compute all pics in a certain folder
#save them color(r,g,b) into colorSpace.json

import Image
import jsTool
import walkfile
size = 16

def aver(k):
    i=0
    sumNum=0
    average=0
    for kk in k:
        i+=1
        sumNum+=kk
        average+=i*kk
    if sumNum!=0:
        return average/sumNum
    else :
        return 0

        
def getColor(filename):
    img = Image.open(filename)
    his=img.resize((100,100),Image.BILINEAR).convert('RGB').histogram()

    r=img.histogram()[:256]
    g=img.histogram()[256:512]
    b=img.histogram()[512:768]
    
    return [aver(r),aver(g),aver(b)]

def pic2space(filename,space):
    try:
        c = getColor(filename)
        
        print c
        space[c[0]*size/256][c[1]*size/256][c[2]*size/256][filename]=c
    except Exception ,e:
        print e
        print 'fail to pic2space on ', filename
        
def searchPic(color,space):
    t=256/size
    threshold = 2
    
    

def main(picpath):
    print picpath
    ''' color space  cSpace[r][g][b]={filename:[r,g,b]}
        e.g. {'/home/nilin/Pictures/santa.jpg': [171, 124, 123]}       '''

    cSpace = [[[ {} for r in range(size)]
                      for g in range(size)]
                          for b in range(size)]
                          
    #cSpace = jsTool.j2o('colorSpace.json')
    
    flist=walkfile.filelist(picpath)
    for f in flist :
        print f
        pic2space(f,cSpace)

    
    
    print cSpace
    jsTool.o2j(cSpace,'colorSpace.json')

    '''get file by color'''

if __name__=='__main__':
    main('home')

